package fr.emn.fil.soc.gr3.restws.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import fr.emn.fil.soc.gr3.entites.Compte;
import fr.emn.fil.soc.gr3.entites.Sujet;
import fr.emn.fil.soc.gr3.restws.DBConnection;
import fr.emn.fil.soc.gr3.restws.ProtocoleCommunication;
import fr.emn.fil.soc.gr3.restws.TokenUtil;

public class ProtocoleCommunicationImpl implements ProtocoleCommunication {

	
	@Override
	public Compte authentifier(String login, String mdp) {
		Compte compte = null;
		DBConnection dbConnection = new DBConnection();
		EntityManager em = dbConnection.createConnection();
	    EntityTransaction transac = em.getTransaction();
	    transac.begin();
	    
		String token = TokenUtil.generateToken();
		try {
			Query query = em.createQuery("SELECT c FROM "
					+ Compte.class.getName()
					+ " c WHERE c.login=:login AND c.password=:password");
			query.setParameter("login", login);
			query.setParameter("password", mdp);
			compte = (Compte) query.getSingleResult();	
			compte.setToken(token);
			em.flush();

		} catch (Exception e) {
			System.err.println(e);
		}
		
		
		transac.commit();
		dbConnection.closeConnection();

		if (compte != null) {
			compte.setPassword("");
		}

		return compte;
	}

	@Override
	public List<Sujet> recupererSujets() {
		List<Sujet> sujets = null;
		DBConnection dbConnection = new DBConnection();
		EntityManager em = dbConnection.createConnection();

		Query query = em.createQuery("SELECT s FROM " + Sujet.class.getName()
				+ " s");
		try {
			sujets = (List<Sujet>) query.getResultList();
		} catch (Exception e) {
			System.err.println(e);
		}

		dbConnection.closeConnection();
		return sujets;
	}

}
